package com.wql.crypto;

import java.security.MessageDigest;
import java.util.Random;

import com.wql.crypto.common.HexUtils;

public class MD5Utils {
	private MD5Utils() {
	}

	private static final String ALGORITHM = "MD5";

	/**
	 * 标准MD5算法
	 * 
	 * @param data
	 * @return
	 */
	public static String md5(String data) {
		if (null != data)
			try {
				MessageDigest md5 = MessageDigest.getInstance(ALGORITHM);
				byte[] bs = md5.digest(data.getBytes());
				return HexUtils.byte2HexStr(bs);
			} catch (Exception e) {
			}
		return null;
	}

	/**
	 * 标准MD5验证方法
	 * 
	 * @param data
	 * @param md5
	 * @return
	 */
	public static boolean verify(String data, String md5) {
		if (null != data)
			return md5(data).equals(md5);
		return false;
	}

	/**
	 * MD5加随机盐，加密后长度为48位，比标准多16位
	 * 
	 * @param data
	 * @return
	 */
	public static String md5WithSalt(String data) {
		Random r = new Random();
		StringBuilder salt = new StringBuilder(16);
		salt.append(r.nextInt(99999999)).append(r.nextInt(99999999));
		int len = salt.length();
		if (len < 16)
			for (int i = 0; i < 16 - len; i++)
				salt.append('0');
		data = md5(data + salt.toString());
		char[] cs = new char[48];
		for (int i = 0; i < 48; i += 3) {
			cs[i] = data.charAt(i / 3 * 2);
			char c = salt.charAt(i / 3);
			cs[i + 1] = c;
			cs[i + 2] = data.charAt(i / 3 * 2 + 1);
		}
		return new String(cs);
	}

	/**
	 * MD5加随机盐验证方法
	 * 
	 * @param data
	 * @param md5
	 * @return
	 */
	public static boolean verifyWithSalt(String data, String md5) {
		if (null != md5 && md5.length() == 48) {
			char[] originMd5 = new char[32];
			char[] salt = new char[16];
			for (int i = 0; i < 48; i += 3) {
				originMd5[i / 3 * 2] = md5.charAt(i);
				originMd5[i / 3 * 2 + 1] = md5.charAt(i + 2);
				salt[i / 3] = md5.charAt(i + 1);
			}
			return verify(data + new String(salt), new String(originMd5));
		}
		return false;
	}
}
